package com.cskaoyan.service;

import com.cskaoyan.bean.*;
import com.cskaoyan.bean.vo.CouponIndexVo;
import com.cskaoyan.mapper.CartMapper;
import com.cskaoyan.mapper.CouponMapper;
import com.cskaoyan.mapper.CouponUserMapper;
import com.cskaoyan.utils.RandomCodeUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class CouponServiceImpl implements CouponService {
    @Autowired
    CouponMapper couponMapper;
    @Autowired
    CouponUserMapper couponUserMapper;
    @Autowired
    CartMapper cartMapper;
    @Override
    public ListData<Coupon> queryList(CouponBO couponBO) {
        PageHelper.startPage(couponBO.getPage(),couponBO.getLimit());
        String name = null;
        if (couponBO.getName()!=null){
             name = "%"+couponBO.getName()+"%";
        }
        String sortAndOrder =couponBO.getSort()+" "+couponBO.getOrder();
        List<Coupon> couponList = couponMapper.selectList(name,couponBO.getType(),couponBO.getStatus(),sortAndOrder);
        ListData<Coupon> couponListData = new ListData<>();
        couponListData.setItems(couponList);
        PageInfo<Coupon> pageInfo = new PageInfo(couponList);
        couponListData.setTotal(pageInfo.getTotal());
        return couponListData;
    }

    @Override
    public Coupon insertCoupon(Coupon coupon) {
        if (coupon.getType()==2){
            String code = RandomCodeUtils.getCode();
            coupon.setCode(code);
        }
        couponMapper.insertSelective(coupon);
        Coupon coupon1 = couponMapper.selectByPrimaryKey(coupon.getId());
        return coupon1;
    }

    @Override
    public Coupon queryCoupon(Integer id) {
        Coupon coupon = couponMapper.selectByPrimaryKey(id);
        return coupon;
    }

    @Override
    public void updateCoupon(Coupon coupon) {
        if (coupon.getType()==2){
            String code = RandomCodeUtils.getCode();
            coupon.setCode(code);
        }
        int update = couponMapper.updateByPrimaryKeySelective(coupon);
    }

    @Override
    public void deleteById(Integer id) {
        Coupon coupon = new Coupon();
        coupon.setId(id);
        coupon.setDeleted(true);
        couponMapper.updateByPrimaryKeySelective(coupon);
    }

    @Override
    public ListData<CouponUser> selectList(CouponUserBO couponUserBO) {
        PageHelper.startPage(couponUserBO.getPage(),couponUserBO.getLimit());
        String sortAndOrder = couponUserBO.getSort() + " "+couponUserBO.getOrder();
        List<CouponUser> couponUserList = couponUserMapper.selectList(couponUserBO.getCouponId(),
                                                            couponUserBO.getUserId(),couponUserBO.getStatus(),sortAndOrder);
        PageInfo<CouponUser> couponUserPageInfo = new PageInfo<>(couponUserList);
        ListData<CouponUser> couponUserListData = new ListData<>();
        couponUserListData.setTotal(couponUserPageInfo.getTotal());
        couponUserListData.setItems(couponUserList);
        return couponUserListData;
    }
    //----------------------------以下小程序接口-----------------------
    @Override
    public ListWxData<CouponIndexVo> queryIndexList(Integer page, Integer size) {
        PageHelper.startPage(page,size);
        Integer type = 0;
        List<CouponIndexVo> list = couponMapper.selectCouponIndex(type);
        //判断是否过期并修改优惠券状态
        int count=0;//记录删除的数量
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i).getEndTime()!=null&&new Date().getTime()>list.get(i).getEndTime().getTime()){
                Coupon coupon = new Coupon();
                coupon.setId(list.get(i).getId());
                coupon.setStatus((short) 1);
                couponMapper.updateByPrimaryKeySelective(coupon);
                list.remove(i);
                i--;
                count++;
            }
        }
        PageInfo<CouponIndexVo> pageInfo = new PageInfo<>(list);
        ListWxData<CouponIndexVo> data = new ListWxData<>();
        data.setData(list);
        data.setCount(pageInfo.getTotal()-count);
        return data;
    }


    // 0 表示领取成功  1 表示卷没了  2表示 达到领取上限
    //3表示优惠券已经兑换  total 为0无限制
    @Override
    public int getCoupon(Integer userId,Integer couponId,String code) {
        Coupon coupon = null;
        if (code==null){
            coupon = couponMapper.selectByPrimaryKey(couponId);
            if (coupon.getTotal()==-1){
                return 1;
            }
            int userCouponCount = couponUserMapper.selectUserCoupon(userId,couponId);
            if (userCouponCount == coupon.getLimit()&&coupon.getLimit()!=0){
                return 2;
            }
        }else {
            coupon = couponMapper.selectByCode(code);
            int count = couponUserMapper.selectUserCoupon(userId, coupon.getId());
            if (coupon.getTotal()==-1){
                return 3;
            }
            if (count==coupon.getLimit()&&coupon.getLimit()!=0){
                return 3;
            }
        }

        //构造插入用户优惠券表
        CouponUser couponUser = new CouponUser();
        couponUser.setUserId(userId);
        couponUser.setCouponId(coupon.getId());
        couponUser.setStatus((short) 0);
        couponUser.setAddTime(new Date());
        couponUser.setUpdateTime(new Date());
        couponUser.setDeleted(false);
        if (coupon.getTimeType()==0){
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(couponUser.getAddTime());
            calendar.add(Calendar.DATE,coupon.getDays());
            Date date = calendar.getTime();
            couponUser.setStartTime(couponUser.getAddTime());
            couponUser.setEndTime(date);
        }else {
            couponUser.setStartTime(coupon.getStartTime());
            couponUser.setEndTime(coupon.getEndTime());
        }
        couponUserMapper.insertSelective(couponUser);
        //减优惠券剩余数
        if(coupon.getTotal()!=0){
            Coupon minusTotal = new Coupon();
            minusTotal.setId(coupon.getId());
            if (coupon.getTotal()==1){
                minusTotal.setTotal(coupon.getTotal()-2);
            }else {
                minusTotal.setTotal(coupon.getTotal()-1);
            }
            couponMapper.updateByPrimaryKeySelective(minusTotal);
        }
        return 0;
    }

    @Override
    public ListWxData<CouponUserListVO> selectMyList(Integer userId, Integer status, Integer page, Integer size) {
        PageHelper.startPage(page,size);
        List<CouponUserListVO> couponUserListVOS = couponUserMapper.selectMyList(userId,status);
        //判断是否过期并修改优惠券状态
        int count=0;//记录删除的数量
        if (status==0){
            for (int i = 0; i < couponUserListVOS.size(); i++) {
                if (couponUserListVOS.get(i).getEndTime()!=null&&new Date().getTime()>couponUserListVOS.get(i).getEndTime().getTime()){
                    CouponUser couponUser = new CouponUser();
                    couponUser.setStatus((short) 2);
                    couponUser.setId(couponUserListVOS.get(i).getId());
                    couponUserMapper.updateByPrimaryKeySelective(couponUser);
                    couponUserListVOS.remove(i);
                    i--;
                    count++;
                }
            }
        }
        PageInfo<CouponUserListVO> pageInfo = new PageInfo<>(couponUserListVOS);
        ListWxData<CouponUserListVO> data = new ListWxData<>();
        data.setCount(pageInfo.getTotal()-count);
        data.setData(couponUserListVOS);
        return data;
    }

    @Override
    public List<CouponUserListVO> selectCanUseCoupon(Integer cartId, Integer userId) {
        BigDecimal price = null;
        if (cartId==0){
            price = BigDecimal.ZERO;
            CartExample cartExample = new CartExample();
            cartExample.createCriteria().andCheckedEqualTo(true).andDeletedEqualTo(false).andUserIdEqualTo(userId);
            // 获取商品信息
            List<Cart> carts = new ArrayList<>();
            carts = cartMapper.selectByExample(cartExample);
            // 求商品总金额
            for (Cart cart : carts) {
                price = price.add(cart.getPrice().multiply(BigDecimal.valueOf(cart.getNumber().longValue())));
            }
        }else {
            Cart cart = cartMapper.selectByPrimaryKey(cartId);
            price = cart.getPrice();
        }
        Date nowDate = new Date();
        List<CouponUserListVO> listVOS = couponUserMapper.selectCanUseCoupon(nowDate,userId,price);
        return listVOS;
    }

}
